package cn.buk.tms.eotms.dao;

import cn.buk.tms.eotms.entity.EnterpriseBalance;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

import java.util.List;

public abstract class AbstractDao {

	@PersistenceContext
	protected EntityManager em;

	/**
	 * 获取企业客户指定部门的用户名
	 * @return
	 */
	protected List<String> doGetCustomerDepartmentOperator(int ownerId, int customerId, int deptId) {
		if (deptId > 0) {
			return em.createQuery("select o.username from User o " +
											"where o.passengerId in " +
											"(" +
											" select p.id from Passenger p " +
											" where p.enterpriseId = :ownerId " +
											" and p.customer.id = :customerId" +
											" and p.department.id = :departmentId)", String.class)
							.setParameter("ownerId", ownerId)
							.setParameter("customerId", customerId)
							.setParameter("departmentId", deptId)
							.getResultList();
		} else {
			return em.createQuery("select o.username from User o " +
											"where o.passengerId in " +
											"(" +
											" select p.id from Passenger p " +
											" where p.enterpriseId = :ownerId " +
											" and p.customer.id = :customerId" +
											" and p.department.id is null)", String.class)
							.setParameter("ownerId", ownerId)
							.setParameter("customerId", customerId)
							.getResultList();
		}
	}

	/**
	 * 获取指定企业的账户余额
	 * @param authorizer 授权者
	 * @param enterpriseId 被授权
	 * @return
	 */
	protected EnterpriseBalance doGetEnterpriseBalance(final int authorizer, final int enterpriseId) {
		EnterpriseBalance result = null;

		List<EnterpriseBalance> results = em.createQuery("select o from EnterpriseBalance o " +
						"where o.enterpriseId = :enterpriseId and o.authorizer = :authorizer", EnterpriseBalance.class)
						.setParameter("enterpriseId", enterpriseId)
						.setParameter("authorizer", authorizer)
						.getResultList();

		if (results.size() > 0) {
			result = results.get(0);
		} else {
			result = new EnterpriseBalance();
			result.setEnterpriseId(enterpriseId);
			result.setAuthorizer(authorizer);
			em.persist(result);
		}

		return result;
	}

}
